package com.goktech.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("file")
public class FileUploadController {
	
	/**
	 * 打开文件上传页面
	 * @return
	 */
	@RequestMapping("")
	public ModelAndView fileIndex() {
		return new ModelAndView("fileUpload");
	}
	
	@RequestMapping("/files")
	public ModelAndView fileIndexs() {
		return new ModelAndView("fileUploads");
	}
	
	@RequestMapping("/upload")
	public ModelAndView uploadFile(@RequestParam MultipartFile file,
			HttpServletRequest request) {
		System.out.println("开始上传文件！");
		// 获取文件的存储的地址
		String path = request.getSession().getServletContext().getRealPath("res/upload");
		String fileName = file.getOriginalFilename();
		System.out.println(path);
		File targetFile = new File(path,fileName);
		
		if(!targetFile.exists()) {
			targetFile.mkdirs();
		}
		
		try {
			// 保存过程
			file.transferTo(targetFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		ModelAndView mav = new ModelAndView("success");
		mav.addObject("fileUrl", request.getContextPath() + "/res/upload/" + fileName);
		return mav;
		
	}
	
	
	@RequestMapping("/uploadFiles")
	public String uploadFiles(@RequestParam("file") MultipartFile[] files,
			HttpServletRequest request) {
		
		String path = request.getSession().getServletContext().getRealPath("res/upload");
		for(MultipartFile file : files) {
			String fileName = file.getOriginalFilename();
			System.out.println(path);
			File targetFile = new File(path,fileName);
			
			if(!targetFile.exists()) {
				targetFile.mkdirs();
			}
			
			try {
				// 保存过程
				file.transferTo(targetFile);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return "sucess";
	}

}
